package com.yyk.yiliao.ui.gongyong.activity;

import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import androidx.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.cache.UserCacheManager;
import com.yyk.yiliao.ui.home.activity.Reservation_Activity;
import com.yyk.yiliao.ui.login.activity.LogIn_Activity;
import com.yyk.yiliao.ui.message.SendAMessageActivity;
import com.yyk.yiliao.ui.mine.activity.Identity_Activity;
import com.yyk.yiliao.util.DialogUtil;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.bean.OrderdoctorOrder_chatInfo;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.widget.web.ProgressView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.TreeMap;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by lenovo on 2018/4/8.
 * Webview  h5页面
 */

public class WebViewActivity extends BaseActivity {
    private static final String EXTRA_URL = "url";
    //    private              String mUrl      = "http://www.chunmaihealth.com/yyk/views/Hospital/DoctorsInfo.html?from=app&Sources=3&did=11";
    private ProgressView mWebView;
    private ImageView iv_eorr;

    private final static int FILECHOOSER_RESULTCODE = 1;
    private ValueCallback<Uri[]> mUploadMessage;
    private String mUrl;
    private String tv;
    private int doctor_id; //医生Id   可以不用从图文问诊获取
    private String user_id;//用户ID
    private String doctorname;//医生名字
    private int uid;        //判断是否登陆


    protected void init() {

        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setDomStorageEnabled(true);//设置防止无法传参数
        mWebView.setFocusable(true);//设置有焦点
        mWebView.setFocusableInTouchMode(true);//设置可触摸
        if (TextUtils.isEmpty(mUrl)) {
            Toast.makeText(this, "请求地址有误", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            mWebView.setWebViewClient(new SimpleWebViewClient());
            mWebView.getSettings().setJavaScriptEnabled(true);
            mWebView.loadUrl(mUrl);
        }
        mWebView.addJavascriptInterface(this, "ZhongYe");
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_webview;
    }

    @Override
    public void initView() {


        user_id = Hawk.get("uid") + "";
        doctorname = getIntent().getStringExtra("doctorname");
        doctor_id = getIntent().getIntExtra("doctor_id", 0);
        tv = getIntent().getStringExtra("toolbar_tv");
        mUrl = getIntent().getStringExtra(EXTRA_URL);
        mWebView = findViewById(R.id.simple_webview);
        iv_eorr = findViewById(R.id.iv_eorr);
        initToolbar();
        init();
    }

    private void initToolbar() {
        setBackArrow();
        if (!TextUtils.isEmpty(tv)) {
            setTitle(tv);
        }
    }

    @Override
    public void initData() {

    }


    @JavascriptInterface
    public void setCompleted(String type) {
        Logger.i("setCompleted" + type);
        WebViewActivity.this.finish();
    }

    /**
     * 预约挂号
     *
     * @param type
     */
    @JavascriptInterface
    public void GoPay(String type) {
        Logger.i("GoPay" + type);
        //判断是否登陆
        if (uid == 0) {
            DialogUtil.getIntanse().simpleDialog(mActivity, "", "您还未登录，请登录后继续操作", "立即登录", "取消"
                    , new DialogUtil.AlertDialogListenter() {
                        @Override
                        public void queding() {
                            startAct(LogIn_Activity.class);
                        }

                        @Override
                        public void quxiao() {

                        }
                    }).show();

        } else {
            String real = Hawk.get("real");
            //实名认证
            if (real.equals("1")) {
                Intent intent = new Intent();
                intent.putExtra("GoPay", type + "");
                startAct(intent, Reservation_Activity.class, null);
            } else {
                DialogUtil.getIntanse().simpleDialog(mActivity, "", "应国家卫计委要求，预约挂号必须进行实名认证，请完善相关资料后再进行操作", "立即认证", "取消"
                        , new DialogUtil.AlertDialogListenter() {
                            @Override
                            public void queding() {
                                //跳转到认证界面
                                startAct(Identity_Activity.class);
                            }

                            @Override
                            public void quxiao() {

                            }
                        }).show();
            }

        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        mWebView.reload();  //刷新
        uid = Hawk.get("uid", 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            Uri[] a = new Uri[1];
            Uri result = intent == null || resultCode != RESULT_OK ? null
                    : intent.getData();
            Log.i("mrl", result + " ");
            a[0] = result;
            if (result != null) {
                mUploadMessage.onReceiveValue(a);
            }
            mUploadMessage = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.clearHistory();
            try {
                mWebView.stopLoading();
                mWebView.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private class SimpleWebViewClient extends WebViewClient {
        private String chat_id;
        private String pic;
        private String name;
        //        @Override
//        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            Logger.e("预约问诊" + url);
//
//            return false;
//        }


        /**
         * 这里主要处理图文问诊这块逻辑
         *
         * @param view
         * @return
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //截取问号+后面的值
            String substring = url.substring(url.indexOf("?"));
            //把问号去掉
            String replace = substring.replace("?", "");
            //获得 chatid   ___   数组
            String[] split = replace.split("=");
            for (int i = 0; i < split.length; i++) {
                String one = split[0];
                if (one.equals("chatId")) {
                    String two = split[1];
                    String[] split2 = two.split(",");
                    chat_id = split2[0];
                    pic = split2[1];
                    name = split2[2];
                    Logger.e("预约问诊2" + chat_id);
                }

            }
            if (uid == 0) {
                DialogUtil.getIntanse().simpleDialog(mActivity, "", "您还未登录，请登录后继续操作", "立即登录", "取消"
                        , new DialogUtil.AlertDialogListenter() {
                            @Override
                            public void queding() {
                                startAct(LogIn_Activity.class);
                            }

                            @Override
                            public void quxiao() {

                            }
                        }).show();

            } else {
                if (chat_id.equals("null")) {
                    ToastUtil.showShort(mActivity, "该医生未开通聊天服务");
                } else {
                    Map<String, String> map = new TreeMap<>();
                    map.put("user_id", user_id + "");
                    Logger.e("用户id" + user_id);
                    String[] split1 = chat_id.split("_");
                    String s = split1[1];
                    map.put("doctor_id",s );
                    Logger.e("医生sid" +s);
                    //1. 预约挂号 2.私人医生 3.图文问诊 4.音频问诊  5.咨询医生  6.电子处方  7.在线转诊  8.名医问答 9.健康资讯 10.健康讲堂  11.诊后随访
                    map.put("busitype", "3");
                    map.put("sign", Md5Util2.createSign(map));
                    RxUtils.getInstance().retrofit.create(ApiService.class).postOrderdoctorOrder_chat(map)
                            .subscribeOn(Schedulers.io())     //调度线程
                            .observeOn(AndroidSchedulers.mainThread())
                            .unsubscribeOn(Schedulers.io())   //取消订阅
                            .subscribe(new Subscriber<OrderdoctorOrder_chatInfo>() {

                                @Override
                                public void onCompleted() {
                                    //完成的时候调用

                                }

                                @Override
                                public void onError(Throwable e) {
                                    e.printStackTrace();


                                }

                                @Override
                                public void onNext(OrderdoctorOrder_chatInfo info) {
                                    Logger.i("问诊订单提交:" + info.toString());
                                    if (info.getCode() == 1) {
                                        sendTextMessage("【问诊】  医生您好，我购买了您的图文问诊服务", chat_id);
                                        //TODO 保存本地医生字段
                                        String resultName = null;
                                        try {
                                            resultName = URLDecoder.decode(name, "utf-8");
                                        } catch (UnsupportedEncodingException e) {
                                            e.printStackTrace();
                                        }
                                        if (pic == null) {
                                            UserCacheManager.save(chat_id, resultName, null);
                                        } else {
                                            UserCacheManager.save(chat_id, resultName, pic);
                                        }
                                        Intent intent = new Intent();
                                        intent.putExtra(EaseConstant.EXTRA_USER_ID, chat_id);
                                        intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EMMessage.ChatType.Chat);
                                        //这里把昵称传过去
                                        intent.putExtra("doctorname", doctorname);
                                        startAct(intent, SendAMessageActivity.class, null);

                                    }

                                }

                            });
                }
            }

            return true;
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Logger.e("预约问诊2" + request.getUrl().toString());
            String string = request.getUrl().toString();
            //截取问号+后面的值
            String substring = string.substring(string.indexOf("?"));
            //把问号去掉
            String replace = substring.replace("?", "");
            //获得 chatid   ___   数组
            String[] split = replace.split("=");
            for (int i = 0; i < split.length; i++) {
                String one = split[0];
                if (one.equals("chatId")) {
                    String two = split[1];
                    String[] split2 = two.split(",");
                    chat_id = split2[0];
                    pic = split2[1];
                    name = split2[2];
                    Logger.e("预约问诊2" + chat_id);
                }

            }
            if (uid == 0) {
                DialogUtil.getIntanse().simpleDialog(mActivity, "", "您还未登录，请登录后继续操作", "立即登录", "取消"
                        , new DialogUtil.AlertDialogListenter() {
                            @Override
                            public void queding() {
                                startAct(LogIn_Activity.class);
                            }

                            @Override
                            public void quxiao() {

                            }
                        }).show();

            } else {
                if (chat_id.equals("null")) {
                    ToastUtil.showShort(mActivity, "该医生未开通聊天服务");
                } else {
                    Map<String, String> map = new TreeMap<>();
                    map.put("user_id", user_id + "");
                    Logger.e("用户id" + user_id);
                    String[] split1 = chat_id.split("_");
                    String s = split1[1];
                    map.put("doctor_id",s );
                    Logger.e("医生sid" +s);
                    //1. 预约挂号 2.私人医生 3.图文问诊 4.音频问诊  5.咨询医生  6.电子处方  7.在线转诊  8.名医问答 9.健康资讯 10.健康讲堂  11.诊后随访
                    map.put("busitype", "3");
                    map.put("sign", Md5Util2.createSign(map));
                    RxUtils.getInstance().retrofit.create(ApiService.class).postOrderdoctorOrder_chat(map)
                            .subscribeOn(Schedulers.io())     //调度线程
                            .observeOn(AndroidSchedulers.mainThread())
                            .unsubscribeOn(Schedulers.io())   //取消订阅
                            .subscribe(new Subscriber<OrderdoctorOrder_chatInfo>() {

                                @Override
                                public void onCompleted() {
                                    //完成的时候调用

                                }

                                @Override
                                public void onError(Throwable e) {
                                    e.printStackTrace();


                                }

                                @Override
                                public void onNext(OrderdoctorOrder_chatInfo info) {
                                    Logger.i("问诊订单提交:" + info.toString());
                                    if (info.getCode() == 1) {
                                        sendTextMessage("【问诊】  医生您好，我购买了您的图文问诊服务", chat_id);
                                        //TODO 保存本地医生字段
                                        String resultName = null;
                                        try {
                                            resultName = URLDecoder.decode(name, "utf-8");
                                        } catch (UnsupportedEncodingException e) {
                                            e.printStackTrace();
                                        }
                                        if (pic == null) {
                                            UserCacheManager.save(chat_id, resultName, null);
                                        } else {
                                            UserCacheManager.save(chat_id, resultName, pic);
                                        }
                                        Intent intent = new Intent();
                                        intent.putExtra(EaseConstant.EXTRA_USER_ID, chat_id);
                                        intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EMMessage.ChatType.Chat);
                                        //这里把昵称传过去
                                        intent.putExtra("doctorname", doctorname);
                                        startAct(intent, SendAMessageActivity.class, null);

                                    }

                                }

                            });
                }
            }

            return true;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            // super.onReceivedSslError(view, handler, error);
            handler.proceed();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

        }


    }

    //发送消息方法
    //==========================================================================
    protected void sendTextMessage(String content, String chat_id) {
        final EMMessage message = EMMessage.createTxtSendMessage(content, chat_id);
        //设置消息扩展字段
        UserCacheManager.setMsgExt(message);
        message.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
            }

            @Override
            public void onError(int code, String error) {
            }

            @Override
            public void onProgress(int progress, String status) {

            }
        });


        // Send message.  发送消息
        EMClient.getInstance().chatManager().sendMessage(message);

    }


}
